//
//  OAuthViewController.swift
//  weibo
//
//  Created by 陈勇 on 16/2/26.
//  Copyright © 2016年 chenyong. All rights reserved.
//

import UIKit
import SVProgressHUD

//身份验证控制器
class OAuthViewController: UIViewController {
    
    private lazy var webView = UIWebView()
 
    override func loadView() {

        view = webView
        //设置导航栏
        title = "登录新浪微博"
        
        navigationController?.navigationBar.titleTextAttributes = [NSFontAttributeName: UIFont.systemFontOfSize(16)]
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(
        
            title: "取消", style: .Plain, target: self, action: "clickCloseButton")
        
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(
            title: "自动填充",
            style: .Plain,
            target: self,
            action: "clickAutoFillButton")

        

    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        //在纯代码开发中 view 都要指定背景颜色
        view.backgroundColor = UIColor.whiteColor()
        // 加载授权 URL
        webView.loadRequest(NSURLRequest(URL: NetworkTools.sharedTools.oauthURL))
        
        // 设置代理
        webView.delegate = self

    }
    
    //监听方法
    @objc private func clickCloseButton(){
        SVProgressHUD.description()
    
        dismissViewControllerAnimated(true, completion: nil)

    }
    
    /// 自动填充用户信息
    @objc private func clickAutoFillButton() {
        
        let JS = "document.getElementById('userId').value='18661098031';" +
        "document.getElementById('passwd').value='204o608o120';"
        
        // 执行 JS
        webView.stringByEvaluatingJavaScriptFromString(JS)
    }
}
extension OAuthViewController: UIWebViewDelegate{
    
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        // 提示: where 字句没有智能提示，需要先写好再复制
        if let urlString = request.URL?.absoluteString
            
        where !urlString.hasPrefix(NetworkTools.sharedTools.redirectUri){
        
            return true
        }
        
        // 2. 否则判断回调参数，如果授权成功 URL 的`查询字符串`中包含 code 参数
        // query 是 URL `?` 后面所有的内容
        // 1> 判断 query 中是否有 code=
        
            guard let query = request.URL?.query where query.hasPrefix("code=") else {
                print("取消授权")
                dismissViewControllerAnimated(true, completion: nil)

            return false
        }
    
        print("请求字符串 " + query)
        
        // 2> 获得请求码
        let code = query.substringFromIndex("code=".endIndex)
        print("请求码 = \(code)")
        
        // 3> 发起网络请求，做后续操作
        NetworkTools.sharedTools.loadAccessToken(code) { (result) -> () in
            
            guard let result = result else {
                print("您的网络不给力")
                return
            }
            
            UserAccount.sharedUserAccount.updateUserAccount(result)
            
            // 登录成功
            // 1> 通知代理工作
            NSNotificationCenter.defaultCenter().postNotificationName(CZWeiBoLoginSuccessedNotification, object: nil)

            SVProgressHUD.showInfoWithStatus("登录成功")
            
            delay(){
            //关闭视图控制器
                self.clickCloseButton()
            }
            
        }
        return false
    }
    
    func webViewDidStartLoad(webView: UIWebView) {
        
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
        
    }
}

    
